let token = sessionStorage.getItem("token");

// 导出用户excel
function exportData() {
    var url = '/users/export/db';
    var searchValue = $("#seacrhInput").val();
    if (searchValue != '') {
        url = url + '&username=' + searchValue;
        //window.location.href = testurl + '/users/export?username='+searchValue;
    }//else {
    //window.location.href = testurl + '/users/export';
    //}
    var ids = "";
    if (checkedLength > 0) {
        for (var i in moreUserid) {
            ids += "," + moreUserid[i];
        }
        ids = ids.substring(1);
    }
    if (ids != '') {
        url = url + '?ids=' + ids;
    }
    window.open(testurl + url);
}



//添加users关闭模态框
$("#users").on('close.modal.amui', function () {

    $("#reset").trigger("click");
    $("#birth").attr("value", "");
    $("#work_date").attr("value", "");
    $("input[name='sex']").removeAttr("checked");
    $("input[name='nomination_way']").removeAttr("checked");
    $("#touxiang").attr("src", "");
});
//获取选中cheacked的id和个数
var userId = "";
var checkedLength = "";
var moreUserid = [];
//获取value值判断是添加还是修改来调用哪个接口
var isAdd = "";
function check(e) {
    moreUserid = [];
    $.each($('#show input:checkbox:checked'), function () {
        userId = $(this).val();
        moreUserid.push(userId);

    });
    checkedLength = $('#show input:checkbox:checked').length;
}
console.log(userId);
//右侧删除
function del(e) {
    var deleteList = [e];
    if(confirm("确定删除?")){
        $.ajax({
            type: "post",
            url: testurl + "users/deletes",
            contentType: "application/json",
            headers: { "Authorization": "Bearer " + token },
            data: JSON.stringify({
                "ids": deleteList
            }),
            success: function (data) {
                if (data.success === true) {
                    $(".users").html("删除用户");
                    $(".alert").html("删除成功！");
                    $('#my-alert').modal({ target: '#my-alert' });
                    $('#modal1').modal('close');
                    loadData(1);
                } else {

                    $(".users").html("删除用户");
                    $(".alert").html("删除失败！");
                    $('#my-alert').modal({ target: '#my-alert' });
                    $('#modal1').modal('close');
                    loadData(1);
                }
            },
            error: function (data) {
                alert(data)
            }
        });
    }

}
// 右侧修改
function editor(e) {
    $("#update").show();
    $("#go").hide();
    $("#getUserId").val(e);
    $("#username").attr("readonly", true);
    $.ajax({
        url: testurl + "users/detail",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "id": e
        }),
        success: function (data) {
            $("#id").val(data.obj.id);
            $("#username").val(data.obj.username);
            $("#realname").val(data.obj.realname);
            if (data.obj.sex === "0") {
                $("input[name='sex']").eq(0).prop("checked", true);
            } else if (data.obj.sex === "1") {
                $("input[name='sex']").eq(1).prop("checked", true);
            }
            $("#birth").datepicker('setValue', data.obj.birth);
            //头像
            let imgSrc = testurl + data.obj.head_pic;
            $("#touxiang").attr("src", imgSrc);
            $("#minzu").val(data.obj.nation);
            $("#native_place").val(data.obj.native_place);
            $("#zhicheng").val(data.obj.positional);
            $("#health").val(data.obj.health);
            $("#deputy_no").val(data.obj.deputy_no);
            $("#major").val(data.obj.major);
            $("#college").val(data.obj.college);
            $("#xuewei").val(data.obj.degree);
            $("#jieg").val(data.obj.structure);
            $("#presasg").val(data.obj.presasg);
            $("#shenfen").val(data.obj.post_id);
            $("#tuan").val(data.obj.deputy_team);
            $("#dangpai").val(data.obj.party_group);
            $("#work_date").datepicker('setValue', data.obj.work_date);
            if (data.obj.nomination_way === "1") {
                $("input[name='nomination_way']").eq(0).prop("checked", true);
            } else if (data.obj.nomination_way === "2") {
                $("input[name='nomination_way']").eq(1).prop("checked", true);
            }

            $("#edu").val(data.obj.education);
            $("#nation").val(data.obj.nation);


            $("#address").val(data.obj.address);
            $("#tel").val(data.obj.tel);
            $("#home_tel").val(data.obj.home_tel);
            $("#phone").val(data.obj.phone);
            $("#zip_code").val(data.obj.zip_code);
            $("#resume").val(data.obj.resume);
            $("#remark").val(data.obj.remark);
            $("#jiebie").val(data.obj.due_id);
            $("#lianren").val(data.obj.is_continuity);
            $("#buxuan").val(data.obj.is_repair);
            if (data.obj.repair_date === undefined) {
                $("#buxuantime").attr("value", "");
            } else {
                $("#buxuantime").datepicker('setValue', data.obj.repair_date);
            }
        }
    });
}
//封装获取所有的下拉框select
function getListbyType(type) {
    let str = "<option value=\"\">请选择</option>";
    $.ajax({
        url: testurl + "dictionary/list_by_type",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "type": type
        }),
        success: function (data) {
            $.each(data.obj, function (index, value) {
                str += "<option value=\"" + value.value_ + "\">" + value.text_ + "</option>"
            })
            $("#" + type).html(str);
        }
    })
}
//读取头像
function readFile() {
    let reader = new FileReader;
    let file = this.files[0];
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        let base64Code = this.result;
        $("#touxiang").attr("src", base64Code);
    }
}
$(function () {
    // 头像
    let pic1 = document.getElementById("head_pic");
    pic1.addEventListener('change', readFile, false);

    let str2 = "<option value=\"\">请选择</option>"
    //学历
    getListbyType("edu");
    //党派
    getListbyType("dangpai");
    //民族
    getListbyType("minzu");
    //职称
    getListbyType("zhicheng");
    //健康
    getListbyType("health");
    //学位
    getListbyType("xuewei");
    //所属结构
    getListbyType("jieg");
    //身份
    let str4 = "";
    $.ajax({
        url: testurl + "post/list",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({}),
        success: function (data) {
            $.each(data.obj, function (index, value) {
                if (value.id === 2) {
                    str4 += "<option selected value=\"" + value.id + "\">" + value.name + "</option>"
                } else {
                    str4 += "<option value=\"" + value.id + "\">" + value.name + "</option>"
                }

            })
            $("#zhiwei").html(str4);
        }

    })
    //届别
    let str5 = "<option value=\"\">请选择</option>";
    $.ajax({
        url: testurl + "due/list_nopage",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({}),
        success: function (data) {
            $.each(data.obj, function (index, value) {
                str5 += "<option value=\"" + value.id + "\">" + value.name + "</option>"
            })
            $("#jiebie").html(str5);
        }
    })
    //委员团组
    $.ajax({
        url: testurl + "deputy/team/list_nopage",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "type": "1"
        }),
        success: function (data) {
            $.each(data.obj, function (index, value) {
                str2 += "<option value=\"" + value.id + "\">" + value.name + "</option>"
            })
            $("#tuan").html(str2);
        }

    })
    //单位
    let str6 = "";
    $.ajax({
        url: testurl + "organ/list_nopage",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({}),
        success: function (data) {
            $.each(data.obj, function (index, value) {

                str6 += "<option value=\"" + value.id + "\">" + value.organ_name + "</option>"


            })
            $("#organ").html(str6);
        }

    })



    //新建
    $(".buildBtn").click(function () {
        $("#go").show();
        $("#update").hide();
        $("#username").removeAttr("readonly");
    });
    //修改
    $(".changeBtn").click(function () {
        // check();
        if (checkedLength <= 0) {
            $('#my-alert').modal({ target: '#my-alert' });
            $(".users").html("修改用户");
            $(".alert").html("请选择要修改的用户！");
            return false;
        } else if (checkedLength === 1) {

            $.ajax({
                url: testurl + "users/detail",
                type: "post",
                headers: { "Authorization": "Bearer " + token },
                contentType: "application/json",
                data: JSON.stringify({
                    "id": userId
                }),
                success: function (data) {
                    $("#id").val(data.obj.id);
                    $("#username").val(data.obj.username);
                    $("#realname").val(data.obj.realname);
                    $("#sex").val(data.obj.sex);
                    //头像
                    let imgSrc = data.obj.head_pic;
                    $("#touxiang").attr("src", imgSrc);
                    let organ_id = data.obj.organ_id;
                    $(".am-selected-list li[data-index='0']").removeClass("am-checked");
                    $(".am-selected-list li[data-value='" + organ_id + "']").attr("class", "am-checked");
                    $(".am-selected-status").html(data.obj.organ_name);
                    $('#join_date').datepicker('setValue', data.obj.join_dates);

                    $("#education").val(data.obj.education);
                    $("#nation").val(data.obj.nation);
                    $("#birth").val(data.obj.birth);
                    $("#marriage").val(data.obj.marriage);
                    $("#origin_addr").val(data.obj.origin_addr);
                    $("#card_no").val(data.obj.card_no);
                    $("#address").val(data.obj.address);
                    $("#family_addr").val(data.obj.family_addr);
                    $("#tel").val(data.obj.tel);
                    $("#phone").val(data.obj.phone);
                    $("#email").val(data.obj.email);
                    console.log(data.obj.organ_id)
                }
            });
            isAdd = $(".newBuild input").attr("value");
            console.log(isAdd)
        } else if (checkedLength > 1) {
            $('#my-alert').modal({ target: '#my-alert' });
            $(".users").html("修改用户");
            $(".alert").html("同时只能选择一个用户,请选择一个！");
            return false;
        }

    });
    //删除
    $(".delBtn").click(function () {
        if (checkedLength <= 0) {
            $('#my-alert').modal({ target: '#my-alert' });
            $(".users").html("删除用户");
            $(".alert").html("请选择要删除的用户！");
            return false;
        } else {
            if(confirm("确定删除所选委员?")){
                $.ajax({
                    type: "post",
                    url: testurl + "users/deletes",
                    contentType: "application/json",
                    headers: { "Authorization": "Bearer " + token },
                    data: JSON.stringify({
                        "ids": moreUserid
                    }),
                    success: function (data) {
                        if (data.success === true) {
                            $(".users").html("删除用户");
                            $(".alert").html("删除成功！");
                            $('#my-alert').modal({ target: '#my-alert' });
                            $('#modal1').modal('close');
                            loadData(1);
                        } else {

                            $(".users").html("删除用户");
                            $(".alert").html("删除失败！");
                            $('#my-alert').modal({ target: '#my-alert' });
                            $('#modal1').modal('close');
                            loadData(1);
                        }
                    },
                    error: function (data) {
                        alert(data)
                    }
                });
            }
 
        }
    });
    //修改密码
    $(".modifyBtn").click(function () {
        if (checkedLength <= 0) {
            $('#my-alert').modal({ target: '#my-alert' });
            $(".users").html("修改密码");
            $(".alert").html("请选择要修改的用户！");
            return false;
        } else if (checkedLength === 1) {
            $(".newBuild").html("修改密码<a href=\"javascript: void(0)\" class=\"am-close am-close-spin\" data-am-modal-close>&times;</a>");

        } else if (checkedLength > 1) {
            $('#my-alert').modal({ target: '#my-alert' });
            $(".users").html("修改密码");
            $(".alert").html("同时只能选择一个用户,请选择一个！");
            return false;
        }

    });
    // 提交修改密码
    $("#go2").click(function () {
        var password = $("#password1").val();
        var form3 = $("#form3");
        form3.validator({
            submit: function () {
                var formValidity = this.isFormValid();
                if (formValidity) {
                    $.ajax({
                        url: testurl + "users/update_password",
                        type: "post",
                        contentType: "application/json",
                        headers: { "Authorization": "Bearer " + token },
                        data: JSON.stringify({
                            "id": userId,
                            "password": password
                        }),
                        success: function (data) {
                            if (data.success === true) {
                                $(".users").html("修改密码");
                                $(".alert").html("修改成功！");
                                $('#my-alert').modal({ target: '#my-alert' });
                                $('#my-popup').modal('close');
                            } else {
                                $(".users").html("修改密码");
                                $(".alert").html("修改失败！");
                                $('#my-alert').modal({ target: '#my-alert' });
                                $('#my-popup').modal('close');
                            }
                        }
                    });
                    return false
                } else {
                    return false
                }
            }
        });

    });

    //修改用户
    $("#update").click(function () {
        let id = $("#getUserId").val();

        //上传头像
        let head_pic = "";
        // if ($("#changePic").val() === "2"){
        var formdata = new FormData();
        var pic = document.getElementById("head_pic").files;
        for (var j = 0; j < pic.length; j++) {
            formdata.append("" + j + "", pic[j]);
        }
        $.ajax({
            async: false,
            url: testurl + "users/headpic",
            type: "post",
            data: formdata,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                head_pic = data.obj;
            }
        });

        let realname = $("#realname").val();
        let sex = $("input[name='sex']:checked").val();

        let nation = $("#minzu option:selected").val();
        let party_group = $("#dangpai option:selected").val();
        let native_place = $("#native_place").val();
        let positional = $("#zhicheng option:selected").val();
        let health = $("#health option:selected").val();

        let birth = $("#birth").val();
        if (birth === "") {
            birth = null;
        }
        let work_date = $("#birth").val();
        if (work_date === "") {
            work_date = null;
        }
        let major = $("#major").val();
        let education = $("#edu option:selected").val();
        let degree = $("#xuewei option:selected").val();
        let deputy_no = $("#deputy_no").val();
        let college = $("#college").val();
        let nomination_way = $("input[name='nomination_way']:checked").val();
        let deputy_team = $("#tuan option:selected").val();
        let structure = $("#jieg option:selected").val();
        let address = $("#address").val();
        let zip_code = $("#zip_code").val();
        let tel = $("#tel").val();
        let home_tel = $("#home_tel").val();
        let phone = $("#phone").val();
        let resume = $("#resume").val();
        let remark = $("#remark").val();
        let presasg = $("#presasg").val();

        let username = $("#username").val();
        let post_id = $("#zhiwei option:selected").val();
        let due_id = $("#jiebie option:selected").val();
        let is_continuity = $("#lianren option:selected").val();
        let is_repair = $("#buxuan option:selected").val();
        let repair_date = $("#buxuantime").val();
        let str3 = {
            "id": id, "party_group": party_group, "native_place": native_place, "realname": realname, "sex": sex, "nation": nation, "birth": birth,
            "head_pic": head_pic, "positional": positional, "work_date": work_date, "health": health, "deputy_no": deputy_no,
            "major": major, "college": college, "education": education, "degree": degree, "nomination_way": nomination_way,
            "deputy_team": deputy_team, "structure": structure, "address": address, "zip_code": zip_code, "tel": tel, "home_tel": home_tel,
            "phone": phone, "resume": resume, "remark": remark, "presasg": presasg, "username": username, "post_id": post_id,
            "due_id": due_id,//届别
            "is_continuity": is_continuity,//是否连任 1是 0否
            "is_repair": is_repair,//是否补选 1是 0否
            "repair_date": repair_date//补选时间
        };



        if (realname === "" || sex === undefined || birth === "" || nation === "" || party_group === ""
            || deputy_no === "" || education === "" || presasg === "" || deputy_team === "" || phone === "" || username === "") {
            alert("请填写带*必填项！");
            return false;
        } else {
            $.ajax({
                async: false,
                headers: { "Authorization": "Bearer " + token },
                url: testurl + "users/update",
                contentType: "application/json",
                type: "post",
                data: JSON.stringify(str3),
                success: function (data) {
                    if (data.success === true) {
                        $(".users").html("修改用户");
                        $(".alert").html(data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#users').modal('close');
                        loadData(1);
                    } else {

                        $(".users").html("修改用户");
                        $(".alert").html("修改失败：" + data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#users').modal('close');
                        loadData(1);
                    }
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }



    });
    //选中所有的checkbox框
    $('#checkAll[name="selectAll"]').click(function () {
        // alert(this.checked);
        if ($(this).is(':checked')) {
            $('#show input[name="selectAll"]').each(function () {
                //此处如果用attr，会出现第三次失效的情况
                $(this).prop("checked", true);
            });
        } else {
            $('input[name="selectAll"]').each(function () {
                $(this).removeAttr("checked", false);
            });
            //$(this).removeAttr("checked");
        }
    });
    //查询用户列表
    //页数
    var pages = 1;
    // 查找用户
    var realname = "";
    $("#searchValue").click(function () {
        realname = $("#seacrhInput").val();
        loadData();
    });



    function loadData(pageNum) {
        $.ajax({
            url: testurl + "users/list",
            type: "post",
            headers: { "Authorization": "Bearer " + token },
            contentType: "application/json",
            data: JSON.stringify({
                "pageNum": pageNum,
                "post_id": "1,2,3",
                "realname": realname,
                "vacancy_flag": "1"
            }),
            success: function (data) {
                let userList = data.obj;
                ssd = Math.ceil(data.pageTotal / data.pageSize);
                pages = ssd;
                str = "";
                $.each(userList, function (index, values) {
                    if (values.phone === null) {
                        values.phone = "";
                    }
                    if (values.email === null) {
                        values.email = "";
                    }
                    str += "   <tr class=\"gradeX\">\n" +
                        "                            <td><input name='selectAll' onchange='check(" + values.id + ")' class='checked' value=" + values.id + " type='checkbox'></td>\n" +
                        "                            <td>" + values.deputy_no + "</td>\n" +
                        "                            <td><a target=\"_blank\" href=\"userInfo.html?id=" + values.id + "\">" + values.realname + "</a></td>\n" +
                        "                            <td>" + values.sex_name + "</td>\n" +
                        "                            <td>" + values.nation_name + "</td>\n" +
                        "                            <td>" + values.presasg + "</td>\n" +
                        "                            <td>" + values.deputy_team_name + "</td>\n" +
                        "                            <td>" + values.phone + "</td>\n" +
                        "                            <td>" + values.vacancy_type_name + "</td>\n" +
                        "                            <td>" + values.vacancy_date + "</td>\n" +
                        "                            <td>\n" +
                        "                                <div class=\"tpl-table-black-operation\">\n" +
                        "                                    <a  data-am-modal=\"{target: '#users'}\"  onclick='editor(\"" + values.id + "\");' href=\"javascript:;\">\n" +
                        "                                        <i class=\"am-icon-pencil\"></i> 修改\n" +
                        "                                    </a>\n" +

                        "                                </div>\n" +
                        "                            </td>\n" +
                        "                        </tr>";
                    // console.log(values.id)
                });
                $("#show").html(str);
                $(".pagenum_1").html(pages)
                if (pageNum >= pages) {
                    pageNum = pages
                }
                $(".strip_1").html(data.pageSize)
                $(".page_1").html(pageNum)
            }
        });
    }
    loadData(1);
    //分页
    var pageNum = 1;
    $(".first").click(function () {
        pageNum = 1;
        loadData(pageNum);
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".last").click(function () {
        pageNum = pages;
        loadData(pageNum);
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".up").click(function () {
        if (pageNum === 1) {
            return false;
        } else {
            pageNum--;
            loadData(pageNum);
        }
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".down").click(function () {
        if (pageNum === pages) {
            return false;
        } else {
            pageNum++;
            loadData(pageNum);
        }
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });


    //出缺
    $("#cancelout").click(function () {
        if (checkedLength <= 0) {
            alert("请选择已出缺委员！");
            return false;
        } else {
            let checkId = $("#cqtype input[name='chuque']:checked").val();
            let ids = moreUserid.toString();
           if(confirm("确定取消出缺?")){
               $.ajax({
                   url: testurl + "users/vacancy",
                   type: "post",
                   headers: { "Authorization": "Bearer " + token },
                   contentType: "application/json",
                   data: JSON.stringify({
                       "ids": ids,
                       "vacancy_flag": "0"
           
                   }),
                   success: function (data) {
                       if (data.success === true) {
                           $(".users").html("取消出缺");
                           $(".alert").html(data.message);
                           $('#my-alert').modal({ target: '#my-alert' });
                         
                           loadData(1);
                       } else {

                           $(".users").html("取消出缺");
                           $(".alert").html("调整失败：" + data.message);
                           $('#my-alert').modal({ target: '#my-alert' });
                
                           loadData(1);
                       }
                   }
               })
           }
   
        }
    })
    //出缺选中确定
    $("#go3").click(function () {

      
        if (checkId === undefined) {
            alert("请选择出缺原因！")
            return false
        } else {
            $.ajax({
                url: testurl + "users/vacancy",
                type: "post",
                headers: { "Authorization": "Bearer " + token },
                contentType: "application/json",
                data: JSON.stringify({
                    "ids": ids,
                    "vacancy_flag": "1",//出缺标志 1出缺 0取消
                    "vacancy_type": checkId//出缺类型 字典CHUQUE
                }),
                success: function (data) {
                    if (data.success === true) {
                        $(".users").html("出缺");
                        $(".alert").html(data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#chuque').modal('close');
                        loadData(1);
                    } else {

                        $(".users").html("出缺");
                        $(".alert").html("调整失败：" + data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#chuque').modal('close');
                        loadData(1);
                    }
                }
            })
        }
    })
});
